package com.mz.demo.config;

import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import com.mz.demo.entity.SysUser;
import com.mz.demo.utils.entity.GloableException;
import com.mz.demo.utils.entity.LoginUser;
import com.mz.demo.utils.tools.JWTUtils;
import com.mz.demo.utils.tools.RedisCache;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class SpringSecurityAuthFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //1、判断 header 中是否存在 token
        String token = request.getHeader("token");
        System.out.println("token: "+token);
        if(!StringUtils.hasText(token)){
            //throw GloableException.gen(10002, "认证失败");
            filterChain.doFilter(request, response);
            return;
        }

        //2、解析 token 获取 userId
        JWT jwt = JWTUtils.getTokenInfo(token);
        JWTPayload jwtPayload = jwt.getPayload();

        JSONObject claimsJson = jwtPayload.getClaimsJson();
        System.out.println("claimsJson: "+claimsJson);
        Long userId =  claimsJson.getLong("id");
        String username = claimsJson.getStr("username");
        System.out.println("userId: "+userId+ ",username:"+username);

        //1、根据用户id获取用户信息
        LoginUser loginUser =  redisCache.getCacheObject( "login:"+userId );
        System.out.println("sysUser: "+loginUser);

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loginUser, null, null );
        SecurityContextHolder.getContext().setAuthentication (authenticationToken);
        filterChain.doFilter(request, response);
    }
}
